import { TokenKey, setToken } from '@/services/auth';
import { request } from 'umi';

const ROOT = '/cpasApi';
const ROOTTE = '/cpasTeApi';

/** 登录接口 需要返回 Response */
async function login(body: any, loginHeader: any): Promise<API.SerResult> {
  const r = await request(`${ROOT}/user/login`, {
    // const r = await request(`${ROOT}/auth/login`, {
    method: 'POST',
    getResponse: true,
    headers: {
      'Content-Type': 'application/json',
      ...loginHeader,
    },
    data: body,
  });
  const { data, response } = r;
  if (data.ok) {
    setToken(response.headers.get(TokenKey)!);
  }
  return r.data;
}

/** 退出接口 */
async function logout(): Promise<API.SerResult> {
  return await request<API.SerResult>(`${ROOT}/user/logout`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
}

/** 获取当前用户信息 接口 */
async function getUserInfo(): Promise<API.SerResult> {
  return await request<API.SerResult>(`${ROOT}/user/getUserInfo`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
}

/**
 * 获取 sql 模板接口数据
 * @param apiName api名称
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
export async function getApiData(apiName: string, params?: any): Promise<API.SerResult> {
  const pd: API.PostData = {
    name: apiName,
  };
  if (params) {
    pd.params = params;
  }
  // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
  try {
    const res = await request<API.SerResult>(`${ROOT}/sqlapis/getApiData?api=${apiName}`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    if (apiName === 'pm.zcbfList') {
      const res2 = await getTeApiData(params);
      const data = res.data.length > 0 ? res.data[0] : {};
      const resData = {
        ...res,
        data: [{
          ...data,
          ...res2.data,
        }],
      };
      return resData;
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

/**
 * 获取 sql 模板接口数据
 * @param apiName api名称
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
export async function getTeApiData(params?: any): Promise<API.SerResult> {
  // const pd: API.PostData = {
  //   name: apiName,
  // };
  // if (params) {
  //   pd.params = params;
  // }
  // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
  try {
    const res = await request<API.SerResult>(`${ROOTTE}/project/${params.projectBh}`, {
      // 云转平台
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      // data: pd,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}


export async function getApisData(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`${ROOT}/sqlapis/getApisData`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

/**
 * 修改表 支持批量
 * @param name 表名（包含数据库名）
 * @param rows 数据
 * @returns 返回执行成功的行数
 */
async function updateTable(name: string, rows: any[]): Promise<API.SerResult> {
  return request<API.SerResult>(`${ROOT}/sqlapis/update`, {
    // 云转平台
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: {
      name,
      rows,
    },
  });
}

export async function getFrameworkVersion(): Promise<any> {
  try {
    const res = await request('/cpasApi/project/version', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return Promise.resolve(res);
  } catch (err) {
    return Promise.resolve('');
  }
}

// 初始化
export async function getInitData(params?: any): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/initZcbf`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}


// 初始化
export async function delZcbfInit(params?: any): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/deleteZcbf`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}



// 初始化
export async function delProjectInit(params?: any): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/deleteProject`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 项目导出
export async function projectExport(params?: any): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/export`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 获取项目导出的进度信息
export async function getExportState(): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/exportState`, {
      // 云转平台
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 获取项目导出的进度信息
export async function getImportState(): Promise<API.SerResult> {

  try {
    const res = await request<API.SerResult>(`/cpasApi/project/importState`, {
      // 云转平台
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}




// 项目导入
export async function projectImport(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`/cpasApi/project/import`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}
// 项目导入
export async function projectExist(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`/cpasApi/project/exist`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 获取导入的包的项目信息
export async function projectInfo(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`/cpasApi/project/getProjectDataPathIfnfo`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

// 项目是否打开
export async function isCheckProjectIsOpened(params?: any): Promise<API.SerResult> {
  try {
    const res = await request<API.SerResult>(`/cpasApi/project/checkProjectIsOpened`, {
      // 云转平台
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: params,
    });
    if (res.code !== 0) {
      // console.log(`请求返回错误,code为：${res.code}`);
    }
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}


/**
 * 获取 nest 接口数据
 * @param apiURL api请求接口地址
 * @param apiMethod api请求方式
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
async function getNestApiData(apiURL: string, apiMethod: string, params?: any): Promise<any> {
  const apiMethodTo = apiMethod ? apiMethod.toUpperCase() : 'POST';
  try {    
    const res = await request<any>(`${ROOT}${apiURL}`, {
      method: apiMethodTo,
      data: params,
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}

/**
 * 获取 nestTe 接口数据
 * @param apiURL api请求接口地址
 * @param apiMethod api请求方式
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
async function getNestTeApiData(apiURL: string, apiMethod: string, params?: any): Promise<any> {
  const apiMethodTo = apiMethod ? apiMethod.toUpperCase() : 'POST';
  try {    
    const res = await request<any>(`${ROOTTE}${apiURL}`, {
      method: apiMethodTo,
      data: params,
    });
    return res;
  } catch (error) {
    return Promise.resolve({ data: error, ok: false, code: 100000 });
  }
}



// export
export default getApiData;
export { getNestApiData, getNestTeApiData, getUserInfo, login, logout, updateTable };

